<script setup>
import * as THREE from 'three'
import { onMounted, onUnmounted, ref } from 'vue'
import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls.js'
import { FBXLoader } from 'three/examples/jsm/loaders/FBXLoader'

const containerRef = ref(null)
let controls = null

// 透视相机
const camera = new THREE.PerspectiveCamera(
  40,
  window.innerWidth / window.innerHeight,
  0.1, // 最近距离
  1000 // 最远距离
)
camera.position.set(30, 10, 20) // 相机位置
// scene
const scene = new THREE.Scene()
// 3D 高性能绘图在web 端的实现  OPENGL
// WebGL 是OPENGL 在web 端的实现
// 还是太底层 ， three.js webgl 封装库
const renderer = new THREE.WebGLRenderer({
  antialias: true,
  alpha: true
})
renderer.setSize(window.innerWidth * 0.9, window.innerHeight * 0.8)
const render = () => {
  requestAnimationFrame(render)
  renderer.render(scene, camera)
}
onMounted(() => {
  containerRef.value.appendChild(renderer.domElement)
  renderer.setClearColor('#ccc')
  scene.background = new THREE.Color(0xffffff)
  scene.environment = new THREE.Color(0xffffff)
  render()
  //控制器 遥感镜头
  controls = new OrbitControls(camera, renderer.domElement)
  controls.update()
  //网格地面 比例大小的参照物
  const gridHelper = new THREE.GridHelper(10, 10)
  gridHelper.material.opacity = 0.2
  gridHelper.material.transparent = true
  scene.add(gridHelper)
  const loader = new FBXLoader()
  loader.load(
    '../../../public/csgd.FBX', // 替换为你的 FBX 文件路径
    (object) => {
      object.position.set(0, 0, 0) // 将模型移动到场景中心
      object.scale.set(0.2, 0.2, 0.2) // 缩小比例模型
      // 模型加载成功，将其添加到场景中
      // 创建新材质
      const newMaterial = new THREE.MeshStandardMaterial({
        color: 0x424449, // 设置颜色
        metalness: 1, // 金属度
        roughness: 1 // 粗糙度
      })
      // 遍历模型的所有子对象
      object.traverse((child) => {
        console.log(child)
        if (child.isMesh) {
          // 替换材质
          child.material = newMaterial
          child.material.needsUpdate = true // 确保材质更新
        }
      })
      // 添加光源
      const ambientLight = new THREE.AmbientLight(0xffffff, 1) // 环境光
      scene.add(ambientLight)

      const directionalLight = new THREE.DirectionalLight(0xffffff, 1) // 平行光
      directionalLight.position.set(10, 10, 10) // 设置光源位置
      scene.add(directionalLight)
      scene.add(object)
    },
    (xhr) => {
      // 可选的进度更新回调
      console.log((xhr.loaded / xhr.total) * 100 + '% loaded')
    },
    (error) => {
      // 处理加载错误
      console.error('An error happened while loading the FBX file', error)
    }
  )
})
</script>

<template>
  <div class="sceneDom" ref="containerRef"></div>
</template>

<style scoped lang="scss">
.sceneDom {
  width: 100vw;
  height: 100vh;
}
</style>
